#include "StdAfx.h"
#include "PlayerThread.h"
#include "VocoderController.h"

PlayerThread::PlayerThread(void)
{
	listener = NULL;
	isPlaying = false;
}

PlayerThread::~PlayerThread(void)
{
}

static int outputLength = 4096;
void PlayerThread::Initialize(PlayerThreadListener* listener, unsigned int samplingRate, unsigned int windowLength)
{
	this->listener = listener;
	this->windowLength = windowLength;
	lastOutput.resize(outputLength);
	sf::SoundStream::Initialize(1, samplingRate);
}

bool PlayerThread::OnGetData(Chunk& Data)
{
	Data.NbSamples = outputLength;
	Data.Samples = &(lastOutput[0]);
	unsigned int i=0;
	mutex.Lock();
	for(; i<Data.NbSamples && myBuf.size(); i++)
	{
		lastOutput[i] = myBuf.front();
		myBuf.pop();
	}
	mutex.Unlock();
	if(i<Data.NbSamples)
	{
		for(; i<windowLength; i++)
		{
			lastOutput[i] = 0;
		}
		isPlaying = false;	
		if(listener)
		{
			listener->OnStreamEnded();
		}
		//return false;
	}
	return true;
}

void PlayerThread::Purge()
{
	mutex.Lock();
	while(myBuf.size())
	{
		myBuf.pop();
	}
	isPlaying = false;
	mutex.Unlock();
}

void PlayerThread::AddSamples(short* samples, unsigned int length)
{
	mutex.Lock();
	for(unsigned int i=0; i<length; i++)
	{
		myBuf.push(samples[i]);
	}
	mutex.Unlock();
	
	if(!isPlaying && myBuf.size()>4096*4)
	{
		isPlaying = true;
		Play();
	}
}